/*
 * @Description:
 * @Author: Junhuang
 * @Date: 2022-05-16 14:50:16
 * @LastEditTime: 2022-05-16 16:09:46
 * @LastEditors: Junhuang
 * @Reference:
 */
'use strict';

const Service = require('egg').Service;
class DepartmentService extends Service {
  // 循环更新当前节点一下的所有子节点（递归）的id_path和name_path
  async refreshPath(dept, ids = [], transaction) {
    // const dept = await app.model.Department.findByPk(id, { transaction });
    const children = await dept.getChildren({ transaction });
    if (children.length > 0) {
      await Promise.all(
        children.map(async el => {
          const _id_path = dept.id_path + el.id + ',';
          const _name_path = dept.name_path + el.name + ',';
          const flag = (_id_path !== el.id_path) || (_name_path !== el._name_path);
          if (flag) {
            el.id_path = _id_path;
            el.name_path = _name_path;
            await el.save({ transaction });
            ids.push(el.id);
          }
          await this.refreshPath(el, ids, transaction);
        })
      );
    }
  }

}
module.exports = DepartmentService;
